package com.ly.heart.service.impl;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.ActTaskCommentEntity;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.mapper.KingBaseInventoryStatusMapper;
import com.ly.heart.service.IActModelService;
import com.ly.heart.service.IActTaskCommentService;
import com.ly.heart.service.IKingBaseInventoryStatusService;
import org.springframework.stereotype.Service;
import com.ly.heart.domain.KingBaseInventoryStatusEntity;

import javax.annotation.Resource;

/**
 * 金蝶-库存状态Service业务层处理
 * @author cxl
 * @date 2024-07-22
 */
@Service
public class KingBaseInventoryStatusServiceImpl extends ServiceImpl<KingBaseInventoryStatusMapper, KingBaseInventoryStatusEntity> implements IKingBaseInventoryStatusService {

    @Resource
    private KingBaseInventoryStatusMapper kingBaseInventoryStatusMapper;
    @Resource
    private IActModelService iActModelService;
    @Resource
    private IActTaskCommentService iActTaskCommentService;

    /**
     * 查询金蝶-库存状态
     * @param id 金蝶-库存状态ID
     * @return 金蝶-库存状态
     */
    @Override
    public KingBaseInventoryStatusEntity selectKingBaseInventoryStatusEntityById (String id) {
        return kingBaseInventoryStatusMapper.selectKingBaseInventoryStatusEntityById ( id );
    }

    /**
     * 查询金蝶-库存状态列表
     * @param kingBaseInventoryStatusEntity 金蝶-库存状态
     * @return 金蝶-库存状态
     */
    @Override
    public AjaxResult selectKingBaseInventoryStatusEntityList (KingBaseInventoryStatusEntity kingBaseInventoryStatusEntity) {
        Page<KingBaseInventoryStatusEntity> page = this.page ( new Page<> ( kingBaseInventoryStatusEntity.getPage (), kingBaseInventoryStatusEntity.getLimit () ), new LambdaQueryWrapper<KingBaseInventoryStatusEntity> ().eq ( KingBaseInventoryStatusEntity :: getIsUsed, ConstUtil.IS_USED_YES ) );
        page.getRecords ().forEach ( status -> {
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId ( status.getInstanceId () );
            Optional.ofNullable ( currentTaskVo ).ifPresent ( currentTask -> {
                status.setCurrentTask ( currentTask );
            } );
            //处理最后一个审批人
            ActTaskCommentEntity actTaskCommentEntity = iActTaskCommentService.queryLastComment ( status.getInstanceId () );
            if ( actTaskCommentEntity != null ) {
                status.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                status.setApprovedTime ( actTaskCommentEntity.getCreateTime () );
                status.setApprovedRemark ( actTaskCommentEntity.getRemark () );
            }
        } );
        return AjaxResult.success ( page );
    }

    /**
     * 新增金蝶-库存状态
     * @param kingBaseInventoryStatusEntity 金蝶-库存状态
     * @return 结果
     */
    @Override
    public AjaxResult draft (KingBaseInventoryStatusEntity kingBaseInventoryStatusEntity) {
        kingBaseInventoryStatusEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ();
        kingBaseInventoryStatusEntity.setInventoryStatusCode ( "KCZT".concat ( String.format ( "%08d", count ) ) );
        kingBaseInventoryStatusEntity.setCreateTime ( DateUtils.getNowDate () );
        kingBaseInventoryStatusEntity.setState ( ConstUtil.STATE_IN_DRAFT );
        boolean save = this.save ( kingBaseInventoryStatusEntity );
        if ( ! save ) {
            return AjaxResult.error ( "暂存库存状态失败" );
        }
        return AjaxResult.success ( "暂存库存状态成功", kingBaseInventoryStatusEntity.getId () );
    }

    public AjaxResult submit (KingBaseInventoryStatusEntity kingBaseInventoryStatusEntity) {
        if ( StringUtils.isBlank ( kingBaseInventoryStatusEntity.getId () ) ) {
            return AjaxResult.error ( "请先暂存该单据！" );
        }
        String bizName = "库存状态_";
        StartProcessDto startDto = new StartProcessDto ().
                setBusinessId ( kingBaseInventoryStatusEntity.getId () ).
                setBusinessType ( kingBaseInventoryStatusEntity.getBusinessType () ).setModelId ( kingBaseInventoryStatusEntity.getModelId () ).
                setBusinessName ( bizName.concat ( kingBaseInventoryStatusEntity.getId () ) );
        String instanceId = iActModelService.startProcess ( startDto );
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseInventoryStatusEntity> ().
                set ( KingBaseInventoryStatusEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                set ( KingBaseInventoryStatusEntity :: getInstanceId, instanceId ).
                eq ( KingBaseInventoryStatusEntity :: getId, kingBaseInventoryStatusEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "库存状态提交失败" );
        }
        return AjaxResult.success ( "库存状态提交成功", kingBaseInventoryStatusEntity.getId () );
    }

    /**
     * 修改金蝶-库存状态
     * @param kingBaseInventoryStatusEntity 金蝶-库存状态
     * @return 结果
     */
    @Override
    public AjaxResult updateKingBaseInventoryStatusEntity (KingBaseInventoryStatusEntity kingBaseInventoryStatusEntity) {
        kingBaseInventoryStatusEntity.setLastUpdateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        kingBaseInventoryStatusEntity.setLastUpdateTime ( DateUtils.getNowDate () );
        boolean b = this.updateById ( kingBaseInventoryStatusEntity );
        if ( ! b ) {
            throw new CustomException ( "修改库存状态失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 批量删除金蝶-库存状态
     * 1、检查是否被单据使用，检查
     * @param ids 需要删除的金蝶-库存状态ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteKingBaseInventoryStatusEntityByIds (String[] ids) {
        List<KingBaseInventoryStatusEntity> list = this.list ( new LambdaQueryWrapper<KingBaseInventoryStatusEntity> ().in ( KingBaseInventoryStatusEntity :: getId, ids ) );
        //查询没有被引用且没有审核的，是可被删除的，isDel=1
        List<String> isDelList = list.stream ().filter ( inventory -> ( inventory.getIsDel () == 1 && inventory.getState ().equals ( "-1" ) ) ).map ( KingBaseInventoryStatusEntity :: getId ).collect ( Collectors.toList () );
        if ( isDelList.size () > 0 ) {
            boolean update = this.update ( new LambdaUpdateWrapper<KingBaseInventoryStatusEntity> ().
                    set ( KingBaseInventoryStatusEntity :: getIsUsed, ConstUtil.IS_USED_NO ).
                    set ( KingBaseInventoryStatusEntity :: getLastUpdateBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                    set ( KingBaseInventoryStatusEntity :: getLastUpdateTime, DateUtils.getNowDate () ).
                    in ( KingBaseInventoryStatusEntity :: getId, isDelList ) );
            if ( ! update ) {
                throw new CustomException ( "删除库存状态失败！" );
            }
        }
        StringBuilder stringBuilder = new StringBuilder ( "【" );
        if ( list.stream ().filter ( inventory -> inventory.getIsDel () == 2 ).collect ( Collectors.toList () ).size () > 0 ) {
            //已经被引用
            list.forEach ( inventory -> {
                if ( inventory.getIsDel () == 2 ) {
                    stringBuilder.append ( inventory.getInventoryStatusName () ).append ( " " );
                }
            } );
            stringBuilder.append ( "】被引用，不可删除！" );
            return AjaxResult.error ( stringBuilder.toString () );
        }
        if ( list.stream ().filter ( inventory -> ! inventory.getState ().equals ( "-1" ) ).collect ( Collectors.toList () ).size () > 0 ) {
            //已经被引用
            list.forEach ( inventory -> {
                if ( ! inventory.getState ().equals ( "-1" ) ) {
                    stringBuilder.append ( inventory.getInventoryStatusName () ).append ( " " );
                }
            } );
            stringBuilder.append ( "】已经审核或在审核中，不可删除！" );
            return AjaxResult.error ( stringBuilder.toString () );
        }
        return AjaxResult.success ( "删除库存状态成功" );
    }

    /**
     * 删除金蝶-库存状态信息
     * @param id 金蝶-库存状态ID
     * @return 结果
     */
    @Override
    public AjaxResult disabled (String id) {
        KingBaseInventoryStatusEntity inventoryStatusEntity = this.getById ( id );
        if ( inventoryStatusEntity == null ) {
            throw new CustomException ( "无此库存状态！" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseInventoryStatusEntity> ().
                set ( KingBaseInventoryStatusEntity :: getIsDisabled, inventoryStatusEntity.getIsDisabled () == 1 ? 2 : 1 ).
                set ( KingBaseInventoryStatusEntity :: getDisabledBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                set ( KingBaseInventoryStatusEntity :: getDisabledTime, DateUtils.getNowDate () ).
                eq ( KingBaseInventoryStatusEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( inventoryStatusEntity.getIsDisabled () == 1 ? "禁用库存状态失败！" : "解禁库存状态失败！" );
        }
        return AjaxResult.success ( inventoryStatusEntity.getIsDisabled () == 1 ? "禁用库存状态成功" : "解禁库存状态成功" );
    }

}
